from django.utils.timezone import now
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework import serializers
from user.models import User

class AVTokenObtainPairSerializer(TokenObtainPairSerializer):
    """
    自定义登录认证
    """
    def validate(self, attrs):
        username = attrs.get('username')
        password = attrs.get('password')

        if not username or not password:
            raise serializers.ValidationError('请输入用户名和密码')
        
        try:
            user = User.objects.filter(username=username).first()
            if not user or not user.check_password(password):
                raise serializers.ValidationError('用户名或密码错误')
            user.last_login = now() # 更新用户最后登录时间
            user.save(update_fields=['last_login']) # 保存用户信息
            print(f"用户 {username} 登录成功")
        except User.DoesNotExist:
            raise serializers.ValidationError('用户名或密码错误')
        
        refresh = self.get_token(user)
        
        data = {
            'user_id': user.id,
            'token': str(refresh.access_token),
            'refresh': str(refresh)
        }
        return data

class AVTokenObtainPairView(TokenObtainPairView):
    serializer_class = AVTokenObtainPairSerializer